package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.cons.MsgTemplate;
import cn.ztydata.teachingsystem.heaven.entity.Chapter;
import cn.ztydata.teachingsystem.heaven.entity.ChapterProfile;
import cn.ztydata.teachingsystem.heaven.entity.Resource;
import cn.ztydata.teachingsystem.heaven.service.ChapterOverviewService;
import cn.ztydata.teachingsystem.heaven.service.ChapterService;
import cn.ztydata.teachingsystem.heaven.web.dto.*;
import cn.ztydata.teachingsystem.webservice.result.json.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 章节控制器类
 * Created by chenxin on 2014/12/16.
 */
@Controller
@RequestMapping("/chapter")
public class ChapterController extends BaseController {
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ChapterOverviewService chapterOverviewService;


    /**
     * 获取模块信息
     * @param nodeId 节点ID
     * @return json
     *
     * @author cx
     * @since 2014-12-16
     */
    @RequestMapping(value = "/moduleInfo/{nodeId}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultData<ModuleInfoDto> getModuleInfo(@PathVariable long nodeId) {
        //校验参数
        Assert.isTrue(nodeId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "节点ID"));

        try {
            //获取模块信息
            Chapter chapter = chapterService.getModuleInfo(nodeId);
            //映射到dto类
            ModuleInfoDto result = mapper.map(chapter, ModuleInfoDto.class);

            return new JsonResultData<>(result);
        } catch (ServiceException ex) {
            log.debug("获取模块儿信息失败");
            return new JsonResultData<>(false, ex.getMessage().isEmpty() ? "获取信息失败" : ex.getMessage());
        }
    }

    /**
     * 更新模块信息
     * @param moduleInfoDto 模块信息dto类
     * @return json
     *
     * @author cx
     * @since 2014-12-16
     */
    @RequestMapping(value = "/moduleInfoEdit", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult updateModuleInfo(@Valid @RequestBody ModuleInfoDto moduleInfoDto) {
        //映射到实体类
        Chapter chapter = mapper.map(moduleInfoDto, Chapter.class);

        try {
            //更新模块信息
            chapterService.updateModuleInfo(chapter);
        } catch (ServiceException ex) {
            log.debug("更新模块信息失败");
            return new JsonResultData<>(false, ex.getMessage().isEmpty() ? "保存失败" : ex.getMessage());
        }

        log.debug("更新模块信息成功");
        return new JsonResult(true, "保存成功");
    }

    /**
     * 更新章节概况
     * @param chapterOverviewDto dto类
     * @return json
     *
     * @author cx
     * @since 2014-12-16
     */
    @RequestMapping(value = "/infoEdit", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult updateInfo(@Valid @RequestBody ChapterOverviewDto chapterOverviewDto) {
        try {
            //编辑保存
            chapterOverviewService.updateContent(chapterOverviewDto.getNodeId(), chapterOverviewDto.getType(), chapterOverviewDto.getContent());
        } catch (ServiceException ex) {
            log.debug("更新章节概况失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "保存失败" : ex.getMessage());
        }

        log.debug("更新章节概况成功");
        return new JsonResult(true, "保存成功");
    }

    /**
     * 获取章节概况
     * @param nodeId 节点ID
     * @param type 概况类型
     * @return json
     *
     * @author cx
     * @since 2014-12-16
     */
    @RequestMapping(value = "/info/{nodeId}/{type}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getInfo(@PathVariable long nodeId, @PathVariable int type) {
        //校验参数
        Assert.isTrue(nodeId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "节点"));
        Assert.isTrue(type > 0 && type < 9, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "概况类型"));

        //获取章节概况内容
        ChapterProfile content = chapterOverviewService.getContent(nodeId, type);

        log.debug("获取章节概况");
        return new JsonResultData<>(mapper.map(content, ChapterOverviewDto.class));
    }

    /**
     * 获取章节概况的填写状态
     *
     * @author chenxin
     * @since 2014/12/17
     */
    @RequestMapping(value = "/infoCheck/{nodeId}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultList<Long> getInfoCheck(@PathVariable long nodeId) {
        //校验参数
        Assert.isTrue(nodeId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "节点ID"));

        //获取概况的填写状态
        List<Long> result = chapterOverviewService.getForNull(nodeId);

        log.debug("获取章节概况的填写状态");
        return new JsonResultList<>(result);
    }

    /**
     * 新增章节资源
     *
     * @author chenxin
     * @since 2014/12/17
     */
    @RequestMapping(value = "/rscAdd", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult saveRelation(@Valid @RequestBody ChapterRscDto chapterRscDto) {
        try {
            chapterService.saveRsc(chapterRscDto.getNodeId(), chapterRscDto.getRscId());
        } catch (ServiceException ex) {
            log.debug("新增章节资源失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "保存失败" : ex.getMessage());
        }

        log.debug("正常返回新增章节资源结果");
        return new JsonResult();
    }

    /**
     * 删除章节资源
     *
     * @author chenxin
     * @since 2014/12/17
     */
    @RequestMapping(value = "/removeRsc/{rscId}/{nodeId}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult deleteRelation(@PathVariable long rscId, @PathVariable long nodeId) {
        //删除关系
        chapterService.deleteRsc(nodeId, rscId);

        log.debug("返回删除章节资源结果");
        return new JsonResult();
    }

    /**
     * 获取章节的资源列表
     *
     * @author chenxin
     * @since 2014/12/17
     */
    @RequestMapping(value = "/rscList/{pageNum}/{pageSize}/{nodeId}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage<ChapterRscDto> getRscList(@PathVariable int pageNum, @PathVariable int pageSize, @PathVariable long nodeId) {
        //校验参数
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));
        Assert.isTrue(nodeId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "节点ID"));

        //获取分页列表
        Page<Resource> page = chapterService.getRscList(pageNum, pageSize, nodeId);
        //映射到dto类
        Page<ChapterRscDto> result = new Page<>(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), ChapterRscDto.class));

        log.debug("获取章节的资源列表");
        return new JsonResultPage<>(result);
    }

    /**
     * 编辑节点
     *
     * @author chenxin
     * @since 2014/12/19
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult updateChapterName(@Valid @RequestBody ChapterDto chapterDto) {
        //映射到实体类
        Chapter chapter = mapper.map(chapterDto, Chapter.class);

        try {
            //保存节点
            chapterService.updateChapter(chapter);

            log.debug("返回编辑节点结果");
            return new JsonResult();
        } catch (ServiceException ex) {
            log.debug("编辑节点失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "保存失败" : ex.getMessage());
        }
    }

    /**
     * 新增节点
     *
     * @author chenxin
     * @since 2014/12/19
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResultId saveChapter(@Valid @RequestBody ChapterDto chapterDto) {
        //映射到实体类
        Chapter chapter = mapper.map(chapterDto, Chapter.class);

        try {
            //保存节点
            chapterService.saveChapter(chapter);

            log.debug("新增节点成功");
            return new JsonResultId(chapter.getId(), "保存成功");
        } catch (ServiceException ex) {
            log.debug("新增节点失败");
            return new JsonResultId(false, ex.getMessage().isEmpty() ? "保存失败" : ex.getMessage());
        }
    }

    /**
     * 删除节点
     *
     * @author chenxin
     * @since 2014/12/19
     */
    @RequestMapping(value = "/remove/{nodeId}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult deleteChapter(@PathVariable long nodeId) {
        //校验参数
        Assert.isTrue(nodeId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "节点ID"));

        try {
            //删除节点
            chapterService.deleteChapter(nodeId);

            log.debug("删除节点成功");
            return new JsonResult(true, "删除成功");
        } catch (ServiceException ex) {
            log.debug("删除节点失败");
            return new JsonResultId(false, ex.getMessage().isEmpty() ? "删除失败" : ex.getMessage());
        }
    }

    /**
     * 章节节点拖拽
     *
     * @author chenxin
     * @since 2014/12/22
     */
    @RequestMapping(value = "/move", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult updateChapter(@Valid @RequestBody NodeDto nodeDto) {
        try {
            //更新节点位置
            chapterService.updatePosition(nodeDto.getId(), nodeDto.getOpposite(), nodeDto.getType());
        } catch (ServiceException ex) {
            log.debug("更新节点位置失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "更新失败" : ex.getMessage());
        }

        log.debug("章节节点拖拽结果");
        return new JsonResult();
    }

    /**
     * 获取子节点
     *
     * @author chenxin
     * @since 2014/12/22
     */
    @RequestMapping(value = "/tree/{courseId}", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getTree(@PathVariable long courseId, @RequestParam(value = "id", required = false, defaultValue = "0") long nodeId) {
        //校验参数
        Assert.isTrue(nodeId >= 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "节点ID"));
        Assert.isTrue(courseId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "课程ID"));

        //获取子节点集合
        List<Chapter> sonNodes = chapterService.getList(nodeId, courseId);

        //转换为前端树结构
        List<Map<String, Object>> result = Lists.newArrayList();
        log.debug("转换为前端树结构:for (Chapter node : sonNodes)");
        for (Chapter node : sonNodes) {
            Map<String, Object> obj = Maps.newHashMap();

            obj.put("id", node.getId());
            obj.put("name", node.getName());
            obj.put("isParent", chapterService.isParent(node.getId()));

            result.add(obj);
        }

        log.debug("获取子节点");
        return result;
    }

    /**
     * 拖拽章节资源
     *
     * @author chenxin
     * @since 2014/12/30
     */
    @RequestMapping(value = "/rscMove/{nodeId}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult moveRsc(@PathVariable long nodeId, @Valid @RequestBody NodeDto nodeDto) {
        //校验参数
        Assert.isTrue(nodeId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "节点ID"));

        try {
            //更新节点资源位置
           chapterService.updateRscPosition(nodeId, nodeDto.getId(), nodeDto.getOpposite(), nodeDto.getType());
        } catch (ServiceException ex) {
            log.debug("更新节点资源位置失败");
            return new JsonResult(false, ex.getMessage().isEmpty() ? "更新失败" : ex.getMessage());
        }

        log.debug("拖拽章节资源结果");
        return new JsonResult();
    }

    /**
     * 章节下拉框
     * @param courseId 课程编号
     * @param chapterId 节编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-04-03
     */
    @ResponseBody
    @RequestMapping(value = "/comboList/{courseId}/{chapterId}", method = RequestMethod.GET)
    public JsonResult comboList(@PathVariable Long courseId,@PathVariable Long chapterId){
        return new JsonResultList<>(mapper.mapList(chapterService.getSonsByParentId(courseId, chapterId),ChapterDto.class));
    }
}
